<!-- 仿真配置 -->
<script setup lang="ts">
import type { SimEngineTableData } from "@/common/apis/engine-library/type"
import type { EditTrainBasicInfo } from "@/common/apis/train/type"
import type { FormRules } from "element-plus"
import { getSimEngineOptionsApi } from "@/common/apis/engine-library"
import { updateTaskApi } from "@/common/apis/train"
import { FormTypeEnum } from "@/common/constants/other-keys"
import SelectScn from "@@/components/SelectScn/index.vue"
import { Edit } from "@element-plus/icons-vue"
import { ElMessage } from "element-plus"
import { cloneDeep } from "lodash"

interface Props {
  dialogType: FormTypeEnum
  ruleForm: EditTrainBasicInfo
  isEdit?: boolean
}
const props = defineProps<Props>()
const emit = defineEmits(["update:ruleForm"])

const ruleFormRef = ref()
const tempForm = ref<EditTrainBasicInfo | null>(null)
const dialogVisible = ref<boolean>(false)

const rules = reactive<FormRules>({
  "sim_config.engine_id": [
    { required: true, message: "请选择仿真引擎", trigger: "change" },
    { required: true, message: "请选择仿真引擎", trigger: "blur" }
  ],
  "sim_config.max_step": [
    { required: true, message: "请输入单局最大步数", trigger: "change" },
    { required: true, message: "请输入单局最大步数", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value <= 0 || value > 9999) {
          callback(new Error("步长必须在 0-9999 之间"))
        } else {
          callback()
        }
      },
      trigger: "change"
    }
  ],
  "sim_config.speed_up_ratio": [
    { required: true, message: "请输入仿真倍速", trigger: "change" },
    { required: true, message: "请输入仿真倍速", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value <= 0 || value > 100) {
          callback(new Error("仿真倍速必须在 0-100 之间"))
        } else {
          callback()
        }
      },
      trigger: "change"
    }
  ],
  "sim_config.scn_id": [
    { required: true, message: "请选择想定", trigger: "change" },
    { required: true, message: "请选择想定", trigger: "blur" }
  ]
})
// 选择引擎
const selectedEngine = ref<SimEngineTableData[]>([])

function getSimEngineOptions() {
  getSimEngineOptionsApi().then(({ data }) => {
    selectedEngine.value = data
  })
}

function handleEngineChange(value) {
  const selectedItem = selectedEngine.value.find(item => item.sim_engine_id === value)
  if (selectedItem) {
    localRuleForm.value.sim_config.engineVersion = selectedItem.sim_engine_version
    localRuleForm.value.sim_config.sim_engine_os = selectedItem.sim_engine_os
  }
}

// 打开选择想定抽屉
function handleOpenScnSelect() {
  dialogVisible.value = true
}

// 关闭选择智能体
function handleCloseDialog() {
  dialogVisible.value = false
}

// 处理想定选择
function handleSelectScn(scn: any) {
  localRuleForm.value.sim_config.scn_id = scn.id
  localRuleForm.value.sim_config.scn_name = scn.scnName
}

const localRuleForm = computed({
  get: () => props.ruleForm,
  set: (newValue) => {
    emit("update:ruleForm", newValue)
  }
})

const engineText = computed(() => {
  return selectedEngine.value.reduce((acc, engine) => {
    acc[engine.sim_engine_id] = engine.sim_engine_name
    return acc
  }, {} as Record<string, string>)
})

getSimEngineOptions()

onMounted(() => {
})

// 暴露验证方法给父组件
defineExpose({
  validate: async () => {
    if (!ruleFormRef.value) return true

    try {
      await ruleFormRef.value.validate()
      return true
    } catch (error) {
      console.error('仿真想定验证失败:', error)
      return false
    }
  },
  localRuleForm
})
</script>

<template>
  <div class="steps-wrapper">
    <el-form ref="ruleFormRef" :model="localRuleForm" status-icon :rules="rules" label-position="right"
      label-width="130px" class="fixed-width" inline>
      <div class="cpi-header-title">
        <SvgIcon name="info-title" />
        <span class="cpi-header-text">仿真配置</span>
      </div>
      <div class="engine-config-title">
        <SvgIcon name="info-little-title" class="engine-config-icon" />仿真引擎配置
      </div>
      <template v-if="isEdit || dialogType == FormTypeEnum.CREATE">
        <div>
          <el-row>
            <el-col :span="12">
              <el-form-item label="选择仿真引擎" prop="sim_config.engine_id">
                <el-select v-model="localRuleForm.sim_config.engine_id" placeholder="请选择仿真引擎"
                  @change="handleEngineChange">
                  <el-option v-for="item in selectedEngine" :key="item.sim_engine_id" :label="item.sim_engine_name"
                    :value="item.sim_engine_id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="引擎版本号" prop="sim_config.engineVersion">
                <el-input v-model="localRuleForm.sim_config.engineVersion" disabled placeholder="请输入" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="运行环境" prop="sim_config.sim_engine_os">
                <el-input v-model="localRuleForm.sim_config.sim_engine_os" disabled placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="仿真倍速" prop="sim_config.speed_up_ratio">
                <el-input-number v-model.number="localRuleForm.sim_config.speed_up_ratio" :min="0.1" :max="100"
                  :step="0.1" :precision="1" :controls="false" :formatter="(value) => Number(value).toFixed(1)" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="单局最大步数" prop="sim_config.max_step">
                <template #label>
                  单局最大步数
                  <el-tooltip content="当达到最大步数，单局仿真结束" placement="right">
                    <SvgIcon name="info" class="svg-icon" />
                  </el-tooltip>
                </template>
                <el-input-number v-model.number="localRuleForm.sim_config.max_step" :min="1" :step="1" clearable
                  step-strictly :controls="false" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单局步长">
                <el-input-number v-model.number="localRuleForm.sim_config.single_step_size" :min="0.1" :max="100"
                  :step="0.1" :precision="1" :controls="false" :formatter="(value) => Number(value).toFixed(1)" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </template>
      <template v-else>
        <el-row>
          <el-col :span="12">
            <el-form-item label="选择仿真引擎：">
              {{ $getViewText(engineText[localRuleForm.sim_config.engine_id]) }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="引擎版本号：">
              {{ $getViewText(localRuleForm.sim_config.engineVersion) }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="运行环境：">
              {{ $getViewText(localRuleForm.sim_config.sim_engine_os) }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仿真倍速：">
              {{ localRuleForm.sim_config.speed_up_ratio }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item>
              <template #label>
                单局最大步数
                <el-tooltip content="当达到最大步数，单局仿真结束" placement="right">
                  <SvgIcon name="info" class="svg-icon" />
                </el-tooltip>：
              </template>
              {{ localRuleForm.sim_config.max_step }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单局步长：">
              {{ localRuleForm.sim_config.single_step_size }}
            </el-form-item>
          </el-col>
        </el-row>
      </template>
      <div class="engine-config-title">
        <SvgIcon name="info-little-title" class="engine-config-icon" />
        <span>想定配置</span>
      </div>
      <template v-if="isEdit || dialogType == FormTypeEnum.CREATE">
        <el-form-item label="选择想定" prop="sim_config.scn_id" class="full-width">
          <el-row>
            <span v-if="localRuleForm.sim_config.scn_name" class="selected-scn">
              {{ localRuleForm.sim_config.scn_name }}
            </span>
            <el-button @click="handleOpenScnSelect">
              选择想定
            </el-button>
          </el-row>
        </el-form-item>
      </template>
      <template v-else>
        <el-form-item label="想定：">
          {{ $getViewText(localRuleForm.sim_config.scn_name) }}
        </el-form-item>
      </template>
    </el-form>

    <SelectScn :selected="localRuleForm.sim_config.scn_id" :visible="dialogVisible" @close-dialog="handleCloseDialog"
      @select-item="handleSelectScn" />
  </div>
</template>

<style lang="scss" scoped>
.steps-wrapper {
  padding: 20px;
  width: 100%;
  height: auto;
  background: #031527;
}

:deep(.el-input-number .el-input__inner) {
  text-align: left !important;
}

.full-width {
  width: calc(100% - 32px);
}

:deep(.full-width > .el-form-item__content) {
  display: block !important;
}

.svg-icon {
  fill: rgba($color: #aaaaaa8b, $alpha: 1) !important;
  cursor: pointer;
}

.selected-scn {
  line-height: 32px;
  display: inline-block;
  margin-right: 10px;
  height: 32px;
}

.engine-config-title {
  margin-bottom: 10px;
}

.engine-config-icon {
  margin-right: 10px;
}

.select-scn-btn {
  width: 109px;
  height: 32px;
  background: linear-gradient(180deg, rgba(9, 109, 140, 0) 0%, #095C8C 100%);
  border-radius: 0px 0px 0px 0px;
  border: 1px solid rgba(0, 0, 0, 0.2);
}

.cpi-header-title {
  margin-bottom: 20px;
}

.cpi-header-text {
  margin-left: 6px;
}
</style>
